package com.donleo.security.jwt.controller;

import com.donleo.security.jwt.common.CommonResult;
import com.donleo.security.jwt.model.SysUser;
import com.donleo.security.jwt.service.ISysUserService;
import com.donleo.security.jwt.vo.LoginParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

/**
 * @author liangd
 * date 2020-12-10 15:32
 * code 用户controller
 */
@RestController
@RequestMapping("/user")
public class SysUserController {

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private ISysUserService userService;

    /**
     * 用户登录
     * @param loginParams
     * @return
     */
    @PostMapping("/login")
    public CommonResult login(@RequestBody LoginParams loginParams){
        HashMap<String, String> data = new HashMap<>();
        String token = null;
        try {
            token = userService.login(loginParams);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.validateFailed("用户名或密码错误");
        }
        if (StringUtils.isEmpty(token)){
            return CommonResult.validateFailed("用户名或密码错误");
        }
        data.put("tokenHead",tokenHead);
        data.put("access_token",token);
        // localStorage.setItem("Authorization","Bearer sdsdfdfds")
        // $ajax{data:{},type:"",header:{"Authorization":"Bearer sdsdfdfds"}}
        return CommonResult.success(data);
    }

    /**
     * 用户注册
     * @param sysUser
     * @return
     */
    @PostMapping("/register")
    public CommonResult register(@RequestBody SysUser sysUser){
        boolean b = userService.register(sysUser);
        if (b){
            return CommonResult.success("注册成功");
        }
        return CommonResult.failed("账号已存在");
    }
}
